<?php

class ReviewController extends FrontController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    public $layout = '//layouts/booking';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','asyncUpload','asyncDelete','viewByAptId'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
//	public function actionView($id)
//	{
//		$this->render('view',array(
//			'model'=>$this->loadModel($id),
//		));
//	}

    /**
     * @param $aptId
     * @throws CHttpException
     */
    public function actionViewByAptId($apt_id){

        $model=Review::model()->findByAttributes(array('apt_id'=>$apt_id));
        //CVarDumper::dump($model,10,true);die;
        if(!$model){
            throw new CHttpException(404,Yii::t('frontend','The requested page does not exist.'));
        }
        echo $this->renderPartial('view',array(
            'model'=>$model,
        ));
    }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
        Yii::import('ext.sweekit.web.SwUploadedFile');
        $model=new Review;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Review']))
		{
            $model->images = SwUploadedFile::getInstances($model, 'images');
			$model->attributes=$_POST['Review'];
            if(!user()->isGuest){
                $user=Users::model()->findByPk(user()->id);
                $model->firstname=$user->firstname;
                $model->lastname=$user->lastname;
            }

			if($model->save()){

//                //Change the status to reviewed is yes
//
//                if(intval($model->apt_id)>0){
//                    Appoint::model()->updateByPk($model->apt_id,array('reviewed'=>Appoint::REVIEWED_YES));
//                }


                //Saving Images
                foreach($model->images as $i => $file) {
                    $imageName = $file->getName();
                    $rvPhoto=new ReviewPhoto();
                    //$businessPhoto->path=$file->getName();
                    $rvPhoto->review_id=$model->id;
                    $rvPhoto->id=null;
                    if($rvPhoto->save(false)){
                        $uniqueName = 'review_'.$model->id.'_'.(md5($imageName . time() . $rvPhoto->id)) . '.' . (pathinfo($imageName, PATHINFO_EXTENSION));
                        $targetSavePath = 'files/Review/images/'.$uniqueName;
                        $file->saveAs($targetSavePath);
                        $rvPhoto->path=$uniqueName;
                        $rvPhoto->update(array('path'));
                    }
                    else echo "Not Ok";

                }
                echo "Ok";
            }

            else {
                echo "Not Ok";
                CVarDumper::dump($model->getErrors(),10,true);
            }
				//$this->redirect(array('view','id'=>$model->id));
            if(Yii::app()->request->isAjaxRequest){
                Yii::app()->end();
            }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Review']))
		{


			$model->attributes=$_POST['Review'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
     * By Brian, ok, we are going to open an invitation link for review
     * This is complex logic and must have well test case, otherwise this could make user a litle bit confusion.
     * In term of logic, we check if user is guest then remain user to login to view, but after user login, we must
     * announce user in the case user does not own the appoinment
	 *
	 */
	public function actionIndex()
	{
        $apt_id=Yii::app()->request->getQuery('apt_id',0);
        $ukey= Yii::app()->request->getQuery('ukey','');
        $message="";
        //Ok, we could not release a page for a customer but that customer is not exist
        $customer=Customer::model()->findByAttributes(array('ckey'=>$ukey));
        if(!$customer) die('aaaaaa');
            //throw new CHttpException(404,'The requested page does not exist.');

        //Check if the appointment is booked
        $aptCus=AptCustomer::model()->findByAttributes(array('apt_id'=>$apt_id,'customer_id'=>$customer->id));
        if(!$aptCus) die('bbbbbbb');
            //throw new CHttpException(404,'The requested page does not exist.');

        $appoint=$aptCus->appt;
        //Just want to make sure that the appointment is exist.
        if($appoint===null ||$aptCus->appt->apt_id===null) die('ccccccc');
            //throw new CHttpException(404,'The requested page does not exist.');
        //If user is guest, use user()->id will not hurt. Yii handled this well
        //Just please make sure you guy don't have any use that owned id is zero. :)
        if(Review::isReviewed($appoint->apt_id,user()->id) ===true)
            $model=Review::model()->findByAttributes(array('apt_id'=>$apt_id));
        else $model=new Review();
        //Just only user login, we have to check and send message to view
        if(!user()->isGuest){
            if($customer->user->id!=user()->id){
                $message=Yii::t('frontend','Sorry but this is an invalid invitation link for you because you might not the owner of the appointment');
            }
        }
        else $message=Yii::t('frontend','Please login to leave a review for this service.');

		$this->render('index',array(
			'appoint'=>$appoint,
			'model'=>$model,
            'message'=>$message
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Review('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Review']))
			$model->attributes=$_GET['Review'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Review the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Review::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,Yii::t('frontend','The requested page does not exist.'));
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Review $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='review-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
